package com.emily.test.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.emily.test.controller.result.ResponseResult;
import com.emily.test.model.OCompanyNavigation;
import com.emily.test.model.ONavigation;
import com.emily.test.service.CompanyNavigationService;
import com.emily.test.service.NavigationService;
import com.emily.test.service.RedisService;
import com.emily.test.utils.ConstentUtil;
import com.emily.test.utils.HeaderUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author ：zc
 * @date ：Created in 2019/3/26 11:12
 * @description：公司导航关联接口
 */
@RestController
@RequestMapping(value = "cn")
@Api(value = "公司导航关联", description = "公司导航关联接口", position = 1, produces = MediaType.APPLICATION_JSON_VALUE)
public class CompanyNavigationController {
    private Logger logger = LoggerFactory.getLogger(CompanyNavigationController.class);
    @Autowired
    private CompanyNavigationService companyNavigationService;

    @Autowired
    private RedisService redisService;
    @Autowired
    private NavigationService navigationService;

    @ApiOperation(value = "获取公司关联导航列表", notes = "获取公司关联导航信息", httpMethod = "POST")
    @PostMapping(value = "/getCNList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "公司id", required = false)
    })
    public ResponseResult getList(@RequestBody(required = false) JSONObject jsonObject, HttpServletRequest request) {
        String token = request.getHeader("token");
        Map<String,Object> userMap= (Map<String, Object>) redisService.get(token);
        Integer companyId=null;
        if(!ConstentUtil.isEmpty(jsonObject)){
            if(!ConstentUtil.isEmpty(jsonObject.getInteger("companyId"))){
                companyId=jsonObject.getInteger("companyId");
            }
        }
        if(!ConstentUtil.isEmpty(userMap)){
            if(!ConstentUtil.isEmpty(userMap.get("companyId"))){

                companyId= userMap.get("companyId") == null ? null : (Integer)userMap.get("companyId");
            }
        }
        try {
            logger.info("获取信息{}",companyId.toString());
            JSONArray jsonArray = new JSONArray();

            List<OCompanyNavigation> list = companyNavigationService.getCompanyNavigationList(companyId);
            for(OCompanyNavigation o :list){
                ONavigation oNavigation =  navigationService.getNavigation(o.getNavicationId());
                JSONObject jsonObjects = new JSONObject();
                jsonObjects.put("id",oNavigation.getId());
                jsonObjects.put("name",oNavigation.getNavigationName());
                jsonObjects.put("englishName",oNavigation.getEnglishName());
                jsonObjects.put("pageurl",oNavigation.getPageurl());
                jsonArray.add(jsonObjects);
            }
            return ResponseResult.success("0", "查询成功", jsonArray);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail("查询失败");
        }
    }

    @ApiOperation(value = "获取公司关联导航列表,已选择的添加selected=1,未选择的添加selected=0", notes = "获取公司关联导航信息", httpMethod = "POST")
    @PostMapping(value = "/getCNListWithInNoSelected")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "公司id", required = false)
    })
    public ResponseResult getCNListWithInNoSelected(HttpServletRequest request) {
        Map<String, Object> userMap =  HeaderUtil.getUserinfo(request,redisService);
        Integer companyId = (Integer) userMap.get("companyId");
        try {
            logger.info("获取信息{}",userMap.values());
            //查询所有启用的导航信息
            List<ONavigation> oNavigationList=navigationService.getNavigationList();
            List<Map<String,Object>> totalMapList = new ArrayList<Map<String,Object>>();
            for(ONavigation nv : oNavigationList){
                Map<String,Object> newMap=ConstentUtil.beanToMap(nv);
                totalMapList.add(newMap);
            }
            //查询公司已经选择了的导航信息
            List<Map<String,Object>> jsonArray = new ArrayList<Map<String,Object>>();
            List<OCompanyNavigation> list = companyNavigationService.getCompanyNavigationList(companyId);
            for(OCompanyNavigation o :list){
                ONavigation oNavigation =  navigationService.getNavigation(o.getNavicationId());
                Map<String,Object> jsonObject=new HashMap<String,Object>();
                jsonObject.put("id",oNavigation.getId());
                jsonObject.put("name",oNavigation.getNavigationName());
                jsonArray.add(jsonObject);
            }
            if(ConstentUtil.isEmpty(oNavigationList)){
               return null;
            }
            for(Map nav : totalMapList){
                Integer navId= (Integer) nav.get("id");
                if(!ConstentUtil.isEmpty(jsonArray)){
                    for(Map<String,Object> js : jsonArray){
                        Integer selectedId= (Integer) js.get("id");
                        if(selectedId.equals(navId)){
                            nav.put("selected","1");
                            break;
                        }else{
                            nav.put("selected","0");
                        }
                    }
                }else{
                    nav.put("selected","0");
                }
            }

            return ResponseResult.success("0", "查询成功", totalMapList);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail("查询失败");
        }
    }

    @ApiOperation(value = "删除公司关联导航", notes = "删除公司关联导航", httpMethod = "POST")
    @PostMapping(value = "/deleteCN")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "导航id列表，格式[1,2,3]", required = true)
    })
    public ResponseResult delete(@RequestBody JSONObject jsonObject) {
        try {
            logger.info("获取信息{}", jsonObject.toJSONString());
            String[] ids = jsonObject.getString("ids").replaceAll("\\[", "").replaceAll("]", "").split(",");
            for (int i = 0; i < ids.length; i++) {
                companyNavigationService.delete(Integer.parseInt(ids[i]));
            }
            return ResponseResult.success("0", "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail("删除失败");
        }
    }

    @ApiOperation(value = "增加/修改公司关联导航", notes = "增加/修改公司关联导航", httpMethod = "POST")
    @PostMapping(value = "/AddModCN")
    @ApiImplicitParams({
//            @ApiImplicitParam(name = "eid", value = "公司id", required = true),
            @ApiImplicitParam(name = "nid", value = "导航id列表[1,2,3]", required = true)
//            @ApiImplicitParam(name = "type", value = "请求类型,add:添加；mod:修改", required = true)
    })
    public ResponseResult addModCN(@RequestBody JSONObject jsonObject,HttpServletRequest request) {
        try {
            logger.info("获取信息{}", jsonObject.toJSONString());
            String token = request.getHeader("token");
            Map<String,Object> userMap= (Map<String, Object>) redisService.get(token);
            Integer companyId= userMap.get("companyId") == null ? null : (Integer)userMap.get("companyId");
//            Integer eid = jsonObject.getInteger("eid");
//            String mod = "mod";
//            if (jsonObject.get("type").equals(mod)) {
                List<OCompanyNavigation> list = companyNavigationService.getCompanyNavigationList(companyId);
                //如果数据库中已经含有公司的导航信息，则此操作为修改，首先去除数据库中导航信息
                if(!ConstentUtil.isEmpty(list)){
                    for (OCompanyNavigation cn : list) {
                        companyNavigationService.delete(cn.getId());
                    }
                }
//            }
            String[] ids = jsonObject.getString("nid").replaceAll("\\[", "").replaceAll("]", "").split(",");
            if(!ConstentUtil.isEmpty(ids)){
                for (int i =0;i<ids.length;i++ ) {
                    OCompanyNavigation oCompanyNavigation = new OCompanyNavigation();
                    oCompanyNavigation.setCompanyId(companyId);
                    oCompanyNavigation.setNavicationId(Integer.parseInt(ids[i].trim()));
                    companyNavigationService.insert(oCompanyNavigation);
                }
            }
            return ResponseResult.success("0", "成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail("失败");
        }
    }
  }
